package com.example.book_recommend.service.impl;

import com.example.book_recommend.dao.UserRoleMapper;
import com.example.book_recommend.entity.UserRole;
import com.example.book_recommend.entity.UserRoleKey;
import com.example.book_recommend.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
public class UserRoleServiceImpl implements UserRoleService {
    @Autowired
    UserRoleMapper userRoleMapper;

    @Override
    public UserRole getOne(Integer userId, Integer roleId) {
        return userRoleMapper.selectByPrimaryKey(new UserRoleKey(userId, roleId));
    }

    @Override
    public Integer[] getRolesByUser(Integer userId) {
        return userRoleMapper.getRolesById(userId);
    }

    @Override
    public int delete(UserRoleKey userRoleKey) {
        return userRoleMapper.deleteByPrimaryKey(userRoleKey);
    }

    @Override
    public int add(UserRole userRole) {
        UserRole userRole1 = userRoleMapper.selectByPrimaryKey(new UserRoleKey(userRole.getUserId(), userRole.getRoleId()));
        if(null == userRole1){
            return userRoleMapper.insert(userRole);
        }
        userRole1.setUpdated(userRole.getUpdated());
        userRoleMapper.updateByPrimaryKey(userRole1);
        return 0;
    }

    @Override
    public int updateUserRoleByRole(Integer oldRoleId, Integer newRoleId) {
        return userRoleMapper.updateByRole(oldRoleId, newRoleId);
    }
}
